const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : '0' + n
}
/**
 * 格式化时间
 */
export const formatTime = (date, type) => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()
  if (type == 'yyyy-mm-dd') {
    return [year, month, day].map(formatNumber).join('-');
  } else if (type == 'yyyy-mm') {
    return [year, month].map(formatNumber).join('-');
  } else if (type == 'mm-dd') {
    return [month, day].map(formatNumber).join('-');
  } else if (type == 'yyyy-mm-dd hh:mm:ss') {
    return [year, month, day].map(formatNumber).join('-') + ' ' + [hour, minute, second].map(formatNumber).join(':')
  } else if (type == 'yyyy-mm-dd hh:mm') {
    return [year, month, day].map(formatNumber).join('-') + ' ' + [hour, minute].map(formatNumber).join(':');
  } else if (type == 'hh:mm') {
    return [hour, minute].map(formatNumber).join(':')
  } else if (type == 'mm-dd hh:mm') {
    return [month, day].map(formatNumber).join('-') + ' ' + [hour, minute].map(formatNumber).join(':');
  } else if (type == 'yyyymmddhhmm') {
    return [year, month, day, hour, minute].map(formatNumber).join('');
  }
}

/**
 * 获取上一个月
 */
export const getLastMonth = () => {
  let date = new Date(new Date().setDate(1) - 86400000);
  let month = date.getMonth() + 1;
  month = month < 10 ? "0" + month : "" + month;
  return date.getFullYear() + '-' + month;
}

/**
 * 获取url参数  返回对象
 */
export const getUrlParams = () => {
  var qs = location.href.split('?')[1];
  var args = {};
  var items = qs.length ? qs.split("&") : [];
  var item = null;
  var len = items.length;

  for (var i = 0; i < len; i++) {
    item = items[i].split("=");
    var name = decodeURIComponent(item[0]);
    var value = decodeURIComponent(item[1]);
    if (name) {
      args[name] = value;
    }
  }
  return args;
}

/**
 * 文件base64转blob
 * @param {*} base64Data 
 */
export const dataURLtoBlob = (base64Data) => {
  var byteString;
  if (base64Data.split(',')[0].indexOf('base64') >= 0)
    byteString = atob(base64Data.split(',')[1]);
  else
    byteString = unescape(base64Data.split(',')[1]);
  var mimeString = base64Data.split(',')[0].split(':')[1].split(";")[0];
  var ia = new Uint8Array(byteString.length);
  for (var i = 0; i < byteString.length; i++) {
    ia[i] = byteString.charCodeAt(i);
  }
  return new Blob([ia], { type: mimeString });
}

/**
 * 生成uuid（32位）
 */
export const generateUUID = () => {
  var d = new Date().getTime();
  if (window.performance && typeof window.performance.now === "function") {
    d += performance.now(); //use high-precision timer if available
  }
  var uuid = 'xxxxxxxxxxxx4xxxyxxxxxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
    var r = (d + Math.random() * 16) % 16 | 0;
    d = Math.floor(d / 16);
    return (c == 'x' ? r : (r & 0x3 | 0x8)).toString(16);
  });
  return uuid;
}

